package com.example.templateapp.ui.login

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.KeyEvent
import androidx.core.app.ActivityCompat
import androidx.lifecycle.rxLifeScope
import com.example.templateapp.R
import com.example.templateapp.databinding.ActivityLoginBinding
import com.example.templateapp.model.LoginInfo
import com.example.templateapp.ui.base.BaseAppCompatActivity
import com.example.templateapp.ui.dropdown.DropDownActivity
import com.example.templateapp.ui.fragment.dialog.WebDialogFragment
import com.example.templateapp.ui.recycler.RecyclerViewActivity
import com.example.templateapp.ui.web.WebViewActivity
import com.example.templateapp.util.LifecycleUtil
import com.example.templateapp.util.UpdateUtil
import com.example.templateapp.util.toActivity
import com.example.templateapp.util.toastException
import com.tencent.mmkv.MMKV
import com.xuexiang.xutil.common.ClickUtils
import com.xuexiang.xutil.tip.ToastUtils
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse

class LoginActivity : BaseAppCompatActivity() {

    private val binding: ActivityLoginBinding by binding(R.layout.activity_login)


    private lateinit var lifecycle: LifecycleUtil

    companion object {
        const val ACCOUNT_KEY = "account"
        const val PW_KEY = "password"


        private const val REQ_PERMISSION = 114
        private val permissions = arrayOf(
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
    }

    private val denyPermissions = mutableListOf<String>()

    private var isAgree = false
    private var isPwLogin = true

    private val loginModel = LoginInfo()

    private lateinit var webDialogFragment: WebDialogFragment


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        initViews()

        setListeners()

        requestPermission()

        lifecycle = LifecycleUtil(this)

        binding.loginModel = loginModel

        rxLifeScope.launch { UpdateUtil.update(this@LoginActivity) }

/*        webDialogFragment = WebDialogFragment("http://118.89.43.183:8085/mobile")
        webDialogFragment.showNow(supportFragmentManager, "")*/
    }


    private fun requestPermission() {

        for (permission in permissions) {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                denyPermissions.add(permission)
            }
        }

        if (denyPermissions.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, denyPermissions.toTypedArray(), REQ_PERMISSION)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == REQ_PERMISSION && permissions.isNotEmpty()) {
            //TODO: 提示权限受限
        }
    }

    private fun initViews() {

        with(MMKV.defaultMMKV()) {
            loginModel.account.value = getString(ACCOUNT_KEY, null)
            loginModel.password.value = getString(PW_KEY, null)
        }
    }


    private fun setListeners() {


        binding.loginBtn.setOnClickListener {
            val account = loginModel.account.value
            val password = loginModel.password.value
            val code = binding.loginVerifyEt.text.toString()

/*            if (isEmptyThenToast(account, "账号") ||
                isEmptyThenToast(password, "密码")
                || isEmptyThenToast(code, "验证码")
            ) return@setOnClickListener

            doLogin(account, password, code)*/

//            toMain()
/*            saveLoginParam()
            toActivity(DropDownActivity::class.java)*/
            toActivity(RecyclerViewActivity::class.java)

        }
//        toActivity(RecyclerViewActivity::class.java)
        binding.serviceAgreementLayout.setOnClickListener { toAgreement() }

    }

    private fun toAgreement() {
        val intent = Intent(this, WebViewActivity::class.java)
        intent.putExtra(WebViewActivity.TITLE_KEY, "敬业物流服务协议")
        intent.putExtra(
            WebViewActivity.URL_KEY,
            "http://118.89.43.183:8085/mobile"
        )
        startActivity(intent)
    }


    private fun doLogin(account: String, password: String, code: String) = rxLifeScope.launch({


        val userRes = RxHttp.postJson("USER.url")
            .add("username", account)
            .toResponse<String>()
            .await()

        ToastUtils.toast(userRes.msg)

        if (userRes.succeed()) {
            saveLoginParam()
            toMain()
        }


    }, { toastException(it) }, { showLoading() }, { disLoading() })


    private fun saveLoginParam() {
        MMKV.defaultMMKV().putString(ACCOUNT_KEY, loginModel.account.value)
        MMKV.defaultMMKV().putString(PW_KEY, loginModel.password.value)
    }

    private fun toMain() {
        toActivity(DropDownActivity::class.java)
//        finish()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ClickUtils.exitBy2Click(2000, object : ClickUtils.OnClick2ExitListener {
                override fun onRetry() {
                    ToastUtils.toast("再按一次退出程序", 500)
                }

                override fun onExit() {
                    finish()
                }
            })
        }
        return true
    }

}